package com.tyj.tuyijiecommon.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <p></p>
 *
 * @author lhf
 * @since 2020/6/8
 */
@EnableConfigurationProperties(SmsProperties.class)
@Component
public class SmsUtil {
    private static Logger log = LoggerFactory.getLogger(SmsUtil.class);
    private HttpClient client = null;
    private PostMethod method = null;

    @Resource
    private SmsProperties properties;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 注册发送验证码
     */
    public String register(String phone) throws Exception {
        log.info("用户{}请求注册验证码", phone);
        int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);

        String content = "您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。";

        NameValuePair[] data = {
                new NameValuePair("account", properties.getAccount()),
                new NameValuePair("password", properties.getPassword()),
                new NameValuePair("mobile", phone),
                new NameValuePair("content", content),
        };
//        发送
        if (!this.send(data)) {
            throw new Exception("验证码发送失败");
        }
        redisTemplate.opsForValue().set("register:code:" + phone, Integer.toString(mobile_code), 5, TimeUnit.MINUTES);
        return Integer.toString(mobile_code);
    }

    /**
     * 登录验证码
     *
     * @param phone
     * @return
     */
    public String login(String phone) throws Exception {
        log.info("用户{}请求登录验证码", phone);
        int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);

        String content = "您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。";

        NameValuePair[] data = {
                new NameValuePair("account", properties.getAccount()),
                new NameValuePair("password", properties.getPassword()),
                new NameValuePair("mobile", phone),
                new NameValuePair("content", content),
        };
//        发送
        if (!this.send(data)) {
            throw new Exception("验证码发送失败");
        }
        redisTemplate.opsForValue().set("login:code:" + phone, Integer.toString(mobile_code), 5, TimeUnit.MINUTES);
        return Integer.toString(mobile_code);
    }

    /**
     * 发送
     *
     * @param data
     */
    public boolean send(NameValuePair[] data) throws Exception {
        client = new HttpClient();
        method = new PostMethod(properties.getUrl());
        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK");

        method.setRequestBody(data);
        client.executeMethod(method);

        String SubmitResult = method.getResponseBodyAsString();

        Document doc = DocumentHelper.parseText(SubmitResult);
        Element root = doc.getRootElement();

        String code = root.elementText("code");
        String msg = root.elementText("msg");
        String smsid = root.elementText("smsid");

        if ("2".equals(code)) {
            return true;
        } else {
            log.error("验证码发送失败!!!!");
            return false;
        }
    }
}
